#include "mystdio.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

#define MODE 0666
#define TRY_FLUSH  1
#define MUST_FLUSH 2

myFILE *myfopen(const char *path, const char *mode)
{
    int fd = -1;
    int flags = 0;
    if (strcmp(mode, "r") == 0)
    {
        fd = open(path, O_RDONLY, MODE);
        flags = O_RDONLY;
    }
    else if (strcmp(mode, "w") == 0)
    {
        fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, MODE);
        flags = O_WRONLY | O_CREAT | O_TRUNC;
    }
    else if (strcmp(mode, "a") == 0)
    {
        fd = open(path, O_WRONLY | O_CREAT | O_APPEND, MODE);
        flags = O_WRONLY | O_CREAT | O_APPEND;
    }
    else 
    {
        // to do
    }

    if (fd == -1)
    {
        return NULL;
    }

    myFILE *fp = (myFILE*)malloc(sizeof(myFILE));
    fp->fd = fd;
    fp->flags = flags;
    fp->flush_mode = LINE_FLUSH;
    fp->pos = 0;
    fp->cap = SIZE;

    return fp;
}

static void myfflushcore(myFILE *fp, int flags)
{
    if (fp->pos == 0)
        return;

    if ((fp->flush_mode & LINE_FLUSH) || flags & MUST_FLUSH)
    {
        // 行缓冲
        if (fp->outbuffer[fp->pos - 1] == '\n' || flags & MUST_FLUSH)
        {
            write(fp->fd, fp->outbuffer, strlen(fp->outbuffer));
            fp->pos = 0;
        }
    }
    else if (fp->flush_mode & FULL_FLUSH)
    {
        // 判断缓冲区是否写满: pos == cap 
        // 写满则调用write
    }
    else if (fp->flush_mode & NONE_FLUSH)
    {
        //write
    }
    else{}

    
}

void myfflush(myFILE *fp)
{
    myfflushcore(fp, MUST_FLUSH);
}

int myfputs(const char* s, myFILE *fp)
{
   if (strlen(s) == 0)
       return 0;
   // 1.将字符串拷贝到语言缓冲区
   // "abcd\n"
   memcpy(fp->outbuffer + fp->pos, s, strlen(s));
   fp->pos += strlen(s);
   // 2.判断是否符合刷新条件
   myfflushcore(fp, TRY_FLUSH);

   return strlen(s);
}


void myfclose(myFILE *fp)
{
    // 强制刷新缓冲区
    myfflush(fp);

    fsync(fp->fd);

    // 关闭内核文件
    close(fp->fd);

    // 释放myFILE
    free(fp);
}
